package thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

import packageHandler.PackageHandlerForClient;
import packageParser.PackageParserForClient;
import protocol.DataPackage;
import frame.ChatFrame;

public class QQClientThread extends Thread{
	private ChatFrame chatRoom;
	private String loginName;
	private BufferedReader reader;
	private BufferedWriter writer;
	private List<String> userList;
	private Socket socket;
	
	public QQClientThread(BufferedReader reader, BufferedWriter writer, String loginName, Socket socket) {
		this.chatRoom = new ChatFrame(loginName, reader, writer);
		this.reader = reader;
		this.writer = writer;
		this.loginName = loginName;
		userList = new ArrayList<String>();
		this.socket = socket;
	}

	@Override
	public void run() {
		
		//发送登录信息
		PackageHandlerForClient.login(reader, writer, loginName);
		System.out.println(loginName + " is login...");
		
		boolean status = true;
		while(status){				
			//返回服务器的确认登录信息
			try{
				String loginString = reader.readLine();
				ObjectMapper mapper = new ObjectMapper();
				DataPackage pack = null;
				try {
					pack = mapper.readValue(loginString, DataPackage.class);
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
				status = PackageParserForClient.packageParseClientReiceive(pack, userList, chatRoom, loginName, writer);
			}
			catch(Exception e){
				System.out.println("服务端断开");
				long nowTime = System.currentTimeMillis();
				SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				String retStrFormatNowDate = sdFormatter.format(nowTime);
				chatRoom.setChatText("server is power down， you will logout... " + retStrFormatNowDate + "\n");
				status = false;
			}
		}
		try {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				System.out.println("待会关闭客户端");
			}
			chatRoom.dispose();
			socket.close();
		} catch (IOException e) {
			System.out.println(loginName + "　用户关闭线程失败");
		}
	}
}
